<template>
  <div class="dashboard-page">
    <!-- 统计卡片区域 -->
    <div class="mb10">
      <!-- 用户统计 -->
      <div class="stats-wrapper">
        <h3 class="stats-title">用户统计</h3>
        <div class="stats-grid">
            <div class="content-stat-card user-card animate-on-enter">
              <div class="content-stat-value">{{ userStatistics.today || 0 }}</div>
              <div class="content-stat-label">今日新增</div>
            </div>

            <div class="content-stat-card user-card animate-on-enter animate-delay-1">
              <div class="content-stat-value">{{ userStatistics.week || 0 }}</div>
              <div class="content-stat-label">本周新增</div>
            </div>

            <div class="content-stat-card user-card animate-on-enter animate-delay-2">
              <div class="content-stat-value">{{ userStatistics.month || 0 }}</div>
              <div class="content-stat-label">本月新增</div>
            </div>

            <div class="content-stat-card user-card animate-on-enter animate-delay-3">
              <div class="content-stat-value">{{ userStatistics.lastMonth || 0 }}</div>
              <div class="content-stat-label">上月新增</div>
            </div>
        </div>
      </div>

      <!-- 帖子统计 -->
      <div class="stats-wrapper">
        <h3 class="stats-title">帖子统计</h3>
        <div class="stats-grid">
            <div class="content-stat-card post-card animate-on-enter animate-delay-4">
              <div class="content-stat-value">{{ postStatistics.today || 0 }}</div>
              <div class="content-stat-label">今日新增</div>
            </div>
            
            <div class="content-stat-card post-card animate-on-enter animate-delay-5">
              <div class="content-stat-value">{{ postStatistics.week || 0 }}</div>
              <div class="content-stat-label">本周新增</div>
            </div>

            <div class="content-stat-card post-card animate-on-enter animate-delay-6">
              <div class="content-stat-value">{{ postStatistics.month || 0 }}</div>
              <div class="content-stat-label">本月新增</div>
            </div>

            <div class="content-stat-card post-card animate-on-enter animate-delay-7">
              <div class="content-stat-value">{{ postStatistics.lastMonth || 0 }}</div>
              <div class="content-stat-label">上月新增</div>
            </div>
          </div>
      </div>

      <!-- 圈子统计 -->
      <div class="stats-wrapper">
        <h3 class="stats-title">圈子统计</h3>
        <div class="stats-grid">
            <div class="content-stat-card topic-card animate-on-enter animate-delay-8">
              <div class="content-stat-value">{{ topicStatistics.today || 0 }}</div>
              <div class="content-stat-label">今日新增</div>
            </div>
            
            <div class="content-stat-card topic-card animate-on-enter animate-delay-9">
              <div class="content-stat-value">{{ topicStatistics.week || 0 }}</div>
              <div class="content-stat-label">本周新增</div>
            </div>

            <div class="content-stat-card topic-card animate-on-enter animate-delay-10">
              <div class="content-stat-value">{{ topicStatistics.month || 0 }}</div>
              <div class="content-stat-label">本月新增</div>
            </div>

            <div class="content-stat-card topic-card animate-on-enter animate-delay-11">
              <div class="content-stat-value">{{ topicStatistics.lastMonth || 0 }}</div>
              <div class="content-stat-label">上月新增</div>
            </div>
        </div>
      </div>
    </div>

  <!-- 图表和信息区域 -->
  <div class="mb10">
    <a-row :gutter="10">
      <!-- 用户增长趋势 -->
      <a-col :xs="24" :lg="16">
        <a-card title="用户增长趋势" class="chart-card animate-on-enter animate-delay-4">
          <div class="chart-container" ref="userGrowthChart"></div>
        </a-card>
      </a-col>

      <!-- 用户分布 -->
      <a-col :xs="24" :lg="8">
        <a-card title="用户分布" class="chart-card animate-on-enter animate-delay-5">
          <div class="chart-container" ref="userDistributionChart"></div>
        </a-card>
      </a-col>
    </a-row>
  </div>

  <!-- 最近日志和系统信息 -->
  <div class="mb10">
    <a-row :gutter="10">
      <!-- 最近操作日志 -->
      <a-col :xs="24" :lg="16">
        <a-card title="最近操作日志" class="logs-card animate-on-enter animate-delay-4" :bordered="false">
          <a-table :columns="logColumns" :data-source="recentLogs" :pagination="false" size="small"
            :scroll="{ x: 800 }">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'is_success'">
                <a-tag :color="record.is_success ? 'success' : 'error'">
                  {{ record.is_success ? '成功' : '失败' }}
                </a-tag>
              </template>
              <template v-if="column.key === 'method'">
                <a-tag :color="getMethodColor(record.method)">{{ record.method }}</a-tag>
              </template>
              <template v-if="column.key === 'duration'">
                <span>{{ record.duration }}ms</span>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-col>

      <!-- 系统信息 -->
      <a-col :xs="24" :lg="8">
        <a-card title="系统信息" class="animate-on-enter animate-delay-5" :bordered="false">
          <div class="system-info">
            <div class="info-item">
              <span class="info-label">PHP版本:</span>
              <span class="info-value">{{ systemInfo.php_version }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">服务器:</span>
              <span class="info-value">{{ systemInfo.server_software }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">内存使用:</span>
              <span class="info-value">{{ systemInfo.memory_usage }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">内存峰值:</span>
              <span class="info-value">{{ systemInfo.memory_peak }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">磁盘空间:</span>
              <span class="info-value">{{ systemInfo.disk_free }} / {{ systemInfo.disk_total }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">服务器时间:</span>
              <span class="info-value">{{ systemInfo.server_time }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">时区:</span>
              <span class="info-value">{{ systemInfo.timezone }}</span>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>
  </div>
  </div>
</template>

<script setup>
import { onMounted, ref, nextTick } from 'vue'
import {
  UserOutlined,
  TeamOutlined,
  FileTextOutlined,
  CrownOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  CalendarOutlined,
  ApartmentOutlined,
  StarOutlined
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import * as echarts from 'echarts'
import {
  getStatistics,
  getRecentLogs,
  getUserGrowth,
  getSystemInfo,
  getUserDistribution,
  getUserStatistics,
  getPostStatistics,
  getTopicStatistics
} from '@/api/dashboard'

// 页面数据
const statistics = ref({})
const recentLogs = ref([])
const userGrowthData = ref([])
const userDistributionData = ref([])
const systemInfo = ref({})
const loading = ref(false)

// 统计数据
const userStatistics = ref({})
const postStatistics = ref({})
const topicStatistics = ref({})

// 图表引用
const userGrowthChart = ref(null)
const userDistributionChart = ref(null)

// 表格列配置
const logColumns = [
  {
    title: '操作者',
    dataIndex: 'operator_name',
    key: 'operator_name',
    width: 100
  },
  {
    title: '请求方法',
    dataIndex: 'method',
    key: 'method',
    width: 80
  },
  {
    title: '请求路径',
    dataIndex: 'uri',
    key: 'uri',
    width: 200,
    ellipsis: true
  },
  {
    title: '操作描述',
    dataIndex: 'description',
    key: 'description',
    width: 150,
    ellipsis: true
  },
  {
    title: '状态',
    dataIndex: 'is_success',
    key: 'is_success',
    width: 80
  },
  {
    title: '耗时',
    dataIndex: 'duration',
    key: 'duration',
    width: 80
  },
  {
    title: 'IP地址',
    dataIndex: 'ip',
    key: 'ip',
    width: 120
  },
  {
    title: '操作时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 150
  }
]

// 页面生命周期
onMounted(async () => {
  await loadDashboardData()
  await nextTick()
  initCharts()
})

// 加载仪表盘数据
const loadDashboardData = async () => {
  loading.value = true
  try {
    // 并行加载所有数据
    const [statsRes, logsRes, growthRes, systemRes, distributionRes] = await Promise.all([
      getStatistics(),
      getRecentLogs({ limit: 10 }),
      getUserGrowth(),
      getSystemInfo(),
      getUserDistribution()
    ])

    if (statsRes.code === 200) {
      statistics.value = statsRes.result
    }

    if (logsRes.code === 200) {
      recentLogs.value = logsRes.result
    }

    if (growthRes.code === 200) {
      userGrowthData.value = growthRes.result
    }

    if (systemRes.code === 200) {
      systemInfo.value = systemRes.result
    }

    if (distributionRes.code === 200) {
      userDistributionData.value = distributionRes.result
    }

    // 加载内容统计数据
    await loadContentStatistics()
  } catch (error) {
    message.error('加载数据失败')
    console.error('Dashboard data loading error:', error)
  } finally {
    loading.value = false
  }
}

// 加载内容统计数据
const loadContentStatistics = async () => {
  try {
    // 并行获取统计数据
    const [userRes, postRes, topicRes] = await Promise.all([
      getUserStatistics(),
      getPostStatistics(),
      getTopicStatistics()
    ])

    // 处理用户统计数据
    if (userRes.code === 200) {
      userStatistics.value = userRes.result
    } else {
      // 如果API失败，使用默认值
      userStatistics.value = {
        today: 0,
        week: 0,
        month: 0,
        lastMonth: 0
      }
    }

    // 处理帖子统计数据
    if (postRes.code === 200) {
      postStatistics.value = postRes.result
    } else {
      postStatistics.value = {
        today: 0,
        week: 0,
        month: 0,
        lastMonth: 0
      }
    }

    // 处理圈子统计数据
    if (topicRes.code === 200) {
      topicStatistics.value = topicRes.result
    } else {
      topicStatistics.value = {
        today: 0,
        week: 0,
        month: 0,
        lastMonth: 0
      }
    }
  } catch (error) {
    console.error('Content statistics loading error:', error)
    // 错误时设置默认值
    userStatistics.value = { today: 0, week: 0, month: 0, lastMonth: 0 }
    postStatistics.value = { today: 0, week: 0, month: 0, lastMonth: 0 }
    topicStatistics.value = { today: 0, week: 0, month: 0, lastMonth: 0 }
  }
}

// 初始化图表
const initCharts = () => {
  initUserGrowthChart()
  initUserDistributionChart()
}

// 初始化用户增长趋势图表
const initUserGrowthChart = () => {
  if (!userGrowthChart.value) return

  const chart = echarts.init(userGrowthChart.value)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: userGrowthData.value.map(item => item.label),
      axisLine: {
        lineStyle: {
          color: '#e8e8e8'
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#e8e8e8'
        }
      }
    },
    series: [
      {
        name: '新增用户',
        type: 'line',
        smooth: true,
        data: userGrowthData.value.map(item => item.count),
        itemStyle: {
          color: '#1890ff'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(24, 144, 255, 0.3)'
              },
              {
                offset: 1,
                color: 'rgba(24, 144, 255, 0.05)'
              }
            ]
          }
        }
      }
    ]
  }

  chart.setOption(option)

  // 响应式
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 初始化用户分布饼图
const initUserDistributionChart = () => {
  if (!userDistributionChart.value) return

  const chart = echarts.init(userDistributionChart.value)

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      textStyle: {
        fontSize: 12
      }
    },
    series: [
      {
        name: '用户分布',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['60%', '50%'],
        data: userDistributionData.value.map(item => ({
          name: item.name,
          value: item.count
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          show: false
        }
      }
    ]
  }

  chart.setOption(option)

  // 响应式
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 工具函数
const getGrowthClass = (rate) => {
  if (rate > 0) return 'growth-positive'
  if (rate < 0) return 'growth-negative'
  return 'growth-neutral'
}

const getMethodColor = (method) => {
  const colors = {
    'GET': 'blue',
    'POST': 'green',
    'PUT': 'orange',
    'DELETE': 'red',
    'PATCH': 'purple'
  }
  return colors[method] || 'default'
}
</script>

<style lang="less" scoped>





.chart-card {
  border-radius: 5px;
  box-shadow: 2px 0 8px #f5f5f5;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
  background: #fff;
  border: none;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 3px;
    background: linear-gradient(90deg, #1890ff, #40a9ff, #69c0ff);
    transform: scaleX(0);
    transform-origin: left;
    transition: transform 0.3s ease;
  }

  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 12px 40px rgba(0, 0, 0, 0.12), 0 6px 20px rgba(0, 0, 0, 0.08);

    &::before {
      transform: scaleX(1);
    }

    :deep(.ant-card-head-title) {
      color: #1890ff;
    }
  }

  :deep(.ant-card-head-title) {
    transition: color 0.3s ease;
  }
}

.chart-container {
  height: 300px;
  width: 100%;
}

.logs-card {
  border-radius: 5px;
  box-shadow: 2px 0 8px #f5f5f5;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
  background: #fff;
  border: none;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 3px;
    background: linear-gradient(90deg, #722ed1, #9254de, #b37feb);
    transform: scaleX(0);
    transform-origin: left;
    transition: transform 0.3s ease;
  }

  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 12px 40px rgba(0, 0, 0, 0.12), 0 6px 20px rgba(0, 0, 0, 0.08);

    &::before {
      transform: scaleX(1);
    }

    :deep(.ant-card-head-title) {
      color: #722ed1;
    }
  }

  :deep(.ant-card-head-title) {
    transition: color 0.3s ease;
  }

  :deep(.ant-table-tbody > tr) {
    transition: all 0.3s ease;

    &:hover {
      background-color: #f8f9fa !important;
      transform: scale(1.01);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    }
  }
}

.system-info {
  .info-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid #f0f0f0;
    transition: all 0.3s;

    &:hover {
      background-color: #fafafa;
      margin: 0 -20px;
      padding-left: 20px;
      padding-right: 20px;
    }

    &:last-child {
      border-bottom: none;
    }
  }

  .info-label {
    font-size: 14px;
    color: #666;
    font-weight: 400;
  }

  .info-value {
    font-size: 14px;
    color: #333;
    font-weight: 500;
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  }
}

.stats-wrapper {
  background-color: white;
  border-radius: 5px;
  padding: 20px;
  margin-bottom: 10px;
}

.stats-title {
  font-size: 16px;
  font-weight: 600;
  color: #616161;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
  margin: -10px;
  padding: 10px;
}

.content-stat-card {
  text-align: center;
  padding: 20px;
}

.content-stat-value {
  font-size: 22px;
  font-weight: 600;
  line-height: 1;
  margin-bottom: 8px;
  color: #595959;
}

.content-stat-label {
  font-size: 14px;
  color: #999;
  margin-bottom: 4px;
  font-weight: 500;
}

.content-stat-desc {
  font-size: 12px;
  color: #666;
  opacity: 0.8;
  display: flex;
  align-items: center;
  gap: 4px;

  .desc-highlight {
    color: #bfbfbf;
    font-weight: 400;
  }

  .desc-number {
    color: #8c8c8c;
    font-weight: 400;
    background: #f0f0f0;
    padding: 2px 8px;
    border-radius: 6px;
    font-size: 12px;
  }
}

</style>